//
//  OAuthViewController.swift
//  XKWeibo
//
//  Created by 小k on 15/11/7.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {


    private lazy var webViwe = UIWebView ()
    
    // MARK: - 监听方法
    @objc private func close () {
    SVProgressHUD.dismiss() // 关闭弹窗
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill () {
        let js = "document.getElementById('userId').value = 'xiaodu520756@163.com';" +
        "document.getElementById('passwd').value = 'duzuokui';"
        
        // 执行js
        webViwe.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // MARK: - 设置界面
    override func loadView() {
        view = webViwe
        
        webViwe.delegate = self
        
        title = "登陆新浪微博"
        
        // 设置导航条
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载界面
        webViwe.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl))
    }
}

// MARK: - UIWebViewDelegate 
extension OAuthViewController: UIWebViewDelegate {
    
    ///  是否加载请求
    ///
    ///  - parameter webView:        webView
    ///  - parameter request:        要加载的请求
    ///  - parameter navigationType: 导航类型
    ///
    ///  - returns: 是否加载当前请求
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 如果是 酷我音乐 就不加载
        // 1. 判断主机地址是否是酷我
        guard let url = request.URL where url.host == "www.kuwo.cn" else {
            return true
        }
        
        // 2. 从酷我地址的 url 中提取 code (授权码) 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            close()             // 取消授权是关闭控制器
            print("取消授权")
            return false
        }

        // 3. 提取授权码
        let code = query.substringFromIndex("code=".endIndex)
        print("授权码是 --" + code)

        // 4. 加载accessToken , 发送请求
        XKUserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
//            print(XKUserAccountViewModel.sharedUserAccount.loadAccessToken)
            if isSuccessed {
                
                SVProgressHUD.dismiss()   // 关闭弹窗
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    // 发送通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewController, object: "welcome")
                })
                
            }else {
                SVProgressHUD.showInfoWithStatus("登陆失败")
                // 添加延时关闭视图控制器
                delay(1.0) {
                    self.close()
                }
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64( NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//                    self.close()
//                })
            }
        }
        return false
    }
    
    // MARK: - SVProgressHUD
    /// 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    /// 结束加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// 加载出错
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        if error?.code == 102 {
            SVProgressHUD.dismiss()
        }else {
            SVProgressHUD.showInfoWithStatus("加载网络失败")
        }
    }
    
}








